package com.zggk.iroad.handle.handleadd;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lxj.matisse.CaptureMode;
import com.lxj.matisse.Matisse;
import com.lxj.matisse.MimeType;
import com.zggk.iroad.R;
import com.zggk.iroad.adapter.recycleview.LGRecycleViewAdapter;
import com.zggk.iroad.adapter.recycleview.LGViewHolder;
import com.zggk.iroad.api.MyAppliCation;
import com.zggk.iroad.db.CzfaInfo;
import com.zggk.iroad.db.EntityManager;
import com.zggk.iroad.db.HandleInfo;
import com.zggk.iroad.greendao.CzfaInfoDao;
import com.zggk.iroad.greendao.HandleInfoDao;
import com.zggk.iroad.mvp.MVPBaseActivity;
import com.zggk.iroad.util.MinePopupWindow;
import com.zggk.iroad.util.MyUtils;
import com.zggk.iroad.util.NoScroolGridView;
import com.zggk.iroad.util.NoScroolRecycle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class HandleAddActivity extends MVPBaseActivity<HandleAddContract.View, HandleAddPresenter> implements HandleAddContract.View {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.xcry_ed)
    TextView xcryEd;
    @Bind(R.id.xcry_lay)
    LinearLayout xcryLay;
    @Bind(R.id.xclx_ed)
    TextView xclxEd;
    @Bind(R.id.xclx_lay)
    LinearLayout xclxLay;
    @Bind(R.id.xcsj_ed)
    TextView xcsjEd;
    @Bind(R.id.xcsj_lay)
    LinearLayout xcsjLay;
    @Bind(R.id.szh_k)
    TextView szhK;
    @Bind(R.id.szh_km)
    TextView szhKm;
    @Bind(R.id.szh_bm)
    TextView szhBm;
    @Bind(R.id.szh_lay)
    LinearLayout szhLay;
    @Bind(R.id.tzh_k)
    TextView tzhK;
    @Bind(R.id.tzh_km)
    TextView tzhKm;
    @Bind(R.id.tzh_bm)
    TextView tzhBm;
    @Bind(R.id.tzh_lay)
    LinearLayout tzhLay;
    @Bind(R.id.disease_shang_txt)
    TextView diseaseShangTxt;
    @Bind(R.id.disease_xia_txt)
    TextView diseaseXiaTxt;
    @Bind(R.id.disease_quan_txt)
    TextView diseaseQuanTxt;
    @Bind(R.id.xsfx_lay)
    LinearLayout xsfxLay;
    @Bind(R.id.bz_lay)
    LinearLayout bzLay;
    @Bind(R.id.bz_et)
    EditText bzEt;
    @Bind(R.id.bhmc_ed)
    TextView bhmcEd;
    @Bind(R.id.bhmc_lay)
    LinearLayout bhmcLay;
    @Bind(R.id.bhsl_te)
    EditText bhslTe;
    @Bind(R.id.dw_te)
    TextView dwTe;
    @Bind(R.id.bhsl_lay)
    LinearLayout bhslLay;
    @Bind(R.id.wxcc_te)
    EditText wxccTe;
    @Bind(R.id.wxcc2_te)
    EditText wxcc2Te;
    @Bind(R.id.wxcc3_te)
    EditText wxcc3Te;
    @Bind(R.id.wxcc_lay)
    LinearLayout wxccLay;
    @Bind(R.id.sgfs_ed)
    TextView sgfsEd;
    @Bind(R.id.sgfs_lay)
    LinearLayout sgfsLay;
    @Bind(R.id.czfa_re)
    NoScroolRecycle czfaRe;
    @Bind(R.id.bz2_et)
    EditText bz2Et;
    @Bind(R.id.cjtp_lay)
    LinearLayout cjtpLay;
    @Bind(R.id.cjtp_ig)
    ImageView cjtpIg;
    @Bind(R.id.sgtp_lay)
    LinearLayout sgtpLay;
    @Bind(R.id.sgtp_im1)
    ImageView sgtpIm1;
    @Bind(R.id.delete_im1)
    ImageView deleteIm1;
    @Bind(R.id.sgtp_im2)
    ImageView sgtpIm2;
    @Bind(R.id.delete_im2)
    ImageView deleteIm2;
    @Bind(R.id.tjtp_lay)
    LinearLayout tjtpLay;
    @Bind(R.id.add_pic_grid)
    NoScroolGridView addPicGrid;
    @Bind(R.id.add_pic_lay)
    LinearLayout addPicLay;
    @Bind(R.id.save_te)
    TextView saveTe;
    @Bind(R.id.add_te)
    TextView addTe;
    @Bind(R.id.add_lay)
    LinearLayout addLay;
    @Bind(R.id.scr_lay)
    ScrollView scrLay;
    private LGRecycleViewAdapter<CzfaInfo> adapter;
    private List<CzfaInfo> Datas = new ArrayList<>();
    private HandleInfo handleInfo;
    private String SGQTP;
    private String SGHTP;
    private MinePopupWindow minePopupWindow;
    private int REQUEST_CODE_CHOOSE = 66;
    private int REQUEST_CODE_CHOOSE2 = 66;
    private int TYPE;
    private HandleAddGird handleAddGird;
    private Map<Integer, HandleAddGird> mapAdapter = new HashMap<>();
    private HandleInfoDao handleInfoDao;
    private CzfaInfoDao czfaInfoDao;

    public void setChildViewPosition(int childViewPosition) {
        this.childViewPosition = childViewPosition;
    }

    private int childViewPosition;//点击拍照获取的childveiw下标

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_handle_add;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        handleInfoDao = EntityManager.getInstance().getHandleInfoDao();
        czfaInfoDao = EntityManager.getInstance().getCzfaInfoDao();
        initAdapter();
        initVew();
    }

    private void initVew() {
        for (int i = 0; i < 10; i++) {
            Log.e("测试",i+"施工维修");
        }
        titleText.setText("施工维修");
        HandleInfoDao handleInfoDao = EntityManager.getInstance().getHandleInfoDao();
        CzfaInfoDao czfaInfoDao = EntityManager.getInstance().getCzfaInfoDao();
        handleInfo = handleInfoDao.loadByRowId(getIntent().getLongExtra("RZID", 0));
        xcryEd.setText(MyAppliCation.spUtils.getString("OrgName"));
        xclxEd.setText(handleInfo.getLXBM());
        xcsjEd.setText(handleInfo.getYQWCSJ());
        String szhStr = handleInfo.getQDZH();
        if (szhStr.contains(".")) {
            String zhone = szhStr.substring(0, szhStr.indexOf("."));
            String zhtwo = szhStr.substring(szhStr.indexOf(".") + 1, szhStr.length());
            szhKm.setText(zhone);
            szhBm.setText(zhtwo);
        } else {
            szhKm.setText(szhStr);
        }
        String tzhStr = handleInfo.getTJQDZH();
        if (tzhStr.contains(".")) {
            String zhone = tzhStr.substring(0, tzhStr.indexOf("."));
            String zhtwo = tzhStr.substring(tzhStr.indexOf(".") + 1, tzhStr.length());
            tzhKm.setText(zhone);
            tzhBm.setText(zhtwo);
        } else {
            tzhKm.setText(tzhStr);
        }
        String xsfxStr = handleInfo.getWZFX();
        if (xsfxStr.equals("上行—右")) {
            ShangSelect();
        } else if (xsfxStr.equals("下行—左")) {
            XiaSelect();
        } else {
            QuanSelect();
        }
        bhmcEd.setText(handleInfo.getBHLX());
        bhslTe.setText(handleInfo.getYGSL());
        dwTe.setText(handleInfo.getBH());
        sgfsEd.setText(handleInfo.getCZFAMC());
        List<CzfaInfo> czfaInfo = czfaInfoDao.queryBuilder().where(CzfaInfoDao.Properties.ParentId.eq(getIntent().getLongExtra("RZID", 0))).list();
        Datas.addAll(czfaInfo);
        adapter.notifyDataSetChanged();
        Glide.with(HandleAddActivity.this)
                .load(handleInfo.getPIC())
                .into(cjtpIg);
        ArrayList<Drawable> listPicture = new ArrayList<>();
        ArrayList<String> listImgUrl = new ArrayList<>();
        Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
        listPicture.add(addPicture);
        final int childPosition = addPicLay.getChildCount();
        handleAddGird = new HandleAddGird(this, listPicture, listImgUrl, childPosition);
        addPicGrid.setAdapter(handleAddGird);
        mapAdapter.put(childPosition, handleAddGird);
    }

    private void ShangSelect() {
        diseaseShangTxt.setTextColor(getResources().getColor(R.color.white));
        diseaseShangTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.up_but_shap));
        diseaseXiaTxt.setTextColor(getResources().getColor(R.color.theme_color));
        diseaseXiaTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
        diseaseQuanTxt.setTextColor(getResources().getColor(R.color.theme_color));
        diseaseQuanTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
    }

    private void XiaSelect() {
        diseaseShangTxt.setTextColor(getResources().getColor(R.color.theme_color));
        diseaseShangTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
        diseaseXiaTxt.setTextColor(getResources().getColor(R.color.white));
        diseaseXiaTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.up_but_shap));
        diseaseQuanTxt.setTextColor(getResources().getColor(R.color.theme_color));
        diseaseQuanTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
    }

    private void QuanSelect() {
        diseaseShangTxt.setTextColor(getResources().getColor(R.color.theme_color));
        diseaseShangTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
        diseaseXiaTxt.setTextColor(getResources().getColor(R.color.theme_color));
        diseaseXiaTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
        diseaseQuanTxt.setTextColor(getResources().getColor(R.color.white));
        diseaseQuanTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.up_but_shap));
    }

    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(HandleAddActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        czfaRe.setLayoutManager(manager);
        czfaRe.setHasFixedSize(true);
        czfaRe.setNestedScrollingEnabled(false);
        adapter = new LGRecycleViewAdapter<CzfaInfo>(Datas) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_handle_czfa;
            }

            @Override
            public void convert(LGViewHolder holder, CzfaInfo zCDBean, int position) {
                holder.setText(R.id.name_te, zCDBean.getGCXM());
                holder.setText(R.id.sl_te, zCDBean.getJSGS());
                holder.setText(R.id.dw_te, zCDBean.getDW());
                final EditText editText = (EditText) holder.getView(R.id.sl_te);
                editText.setTag(position);//存tag值
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        int position = (int) editText.getTag();//取tag值
                        Datas.get(position).setJSGS(s.toString());
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
            }
        };

        czfaRe.setAdapter(adapter);
    }

    @OnClick({R.id.back, R.id.save_te, R.id.add_te, R.id.sgtp_im1, R.id.sgtp_im2
            , R.id.delete_im1, R.id.delete_im2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.save_te:
                handleInfo.setBZ(bzEt.getText().toString());
                handleInfo.setCCONE(wxccTe.getText().toString());
                handleInfo.setCCTWO(wxcc2Te.getText().toString());
                handleInfo.setCCTHREE(wxcc3Te.getText().toString());
                handleInfo.setISDB("1");
                List<CzfaInfo> czfaInfos = czfaInfoDao.queryBuilder().where(CzfaInfoDao.Properties.ParentId.eq(getIntent().getLongExtra("RZID", 0))).list();
                for (int i = 0; i < czfaInfos.size(); i++) {
                    czfaInfos.get(i).setJSGS(Datas.get(i).getJSGS());
                    czfaInfoDao.update(czfaInfos.get(i));
                }
                handleInfoDao.update(handleInfo);
                ToastUtils.showShort("修改成功");
                break;
            case R.id.add_te:
                HandleAddJson handleAddJson = new HandleAddJson();
                handleAddJson.setBHGUID(handleInfo.getBHGUID());
                handleAddJson.setQDZH(handleInfo.getQDZH());
                handleAddJson.setJLDW(handleInfo.getJLDW());
                handleAddJson.setSGDW(MyAppliCation.spUtils.getString("GydwId"));
                handleAddJson.setSGFZR(MyAppliCation.spUtils.getString("OrgName"));
                handleAddJson.setBZ(bzEt.getText().toString());
                handleAddJson.setSLCC("1");
                handleAddJson.setF01(bhslTe.getText().toString());
                handleAddJson.setF02(wxccTe.getText().toString());
                handleAddJson.setF03(wxcc2Te.getText().toString());
                handleAddJson.setF04(wxcc3Te.getText().toString());
                ArrayList<HandleAddJson.PICBean> listPic = new ArrayList<>();
                HandleAddJson.PICBean picBean = new HandleAddJson.PICBean();
                String imgUrl = SGQTP;
                String nameStr = imgUrl.substring(imgUrl.lastIndexOf("/") + 1, imgUrl.length());
                String typeStr = imgUrl.substring(imgUrl.lastIndexOf(".") + 1, imgUrl.length());
                picBean.setPicFileName(nameStr);
                picBean.setPicFileType(typeStr);
                String strBlob = MyUtils.bmpToBase64String(imgUrl);
                picBean.setPicDataBlob(strBlob);
                picBean.setWJLX("0");
                listPic.add(picBean);
                HandleAddJson.PICBean picBean2 = new HandleAddJson.PICBean();
                String imgUrl2 = SGHTP;
                String nameStr2 = imgUrl2.substring(imgUrl2.lastIndexOf("/") + 1, imgUrl2.length());
                String typeStr2 = imgUrl2.substring(imgUrl2.lastIndexOf(".") + 1, imgUrl2.length());
                picBean2.setPicFileName(nameStr2);
                picBean2.setPicFileType(typeStr2);
                String strBlob2 = MyUtils.bmpToBase64String(imgUrl2);
                picBean2.setPicDataBlob(strBlob2);
                picBean2.setWJLX("2");
                listPic.add(picBean2);
                String imgStr2 = "";
                ArrayList<String> listImgUrl2 = handleAddGird.getListImgUrl();
                if (listImgUrl2 != null && listImgUrl2.size() > 0) {
                    for (int k = 0; k < listImgUrl2.size(); k++) {
                        if (k == 0) {
                            imgStr2 += listImgUrl2.get(k);
                        } else {
                            imgStr2 += "," + listImgUrl2.get(k);
                        }
                    }
                }
                if (!StringUtils.isSpace(imgStr2)) {
                    String[] strArr = imgStr2.split(",");
                    if (strArr != null && strArr.length > 0) {
                        for (int i = 0; i < strArr.length; i++) {
                            HandleAddJson.PICBean picInfo = new HandleAddJson.PICBean();
                            String imgUrl3 = strArr[i];
                            String nameStr3 = imgUrl3.substring(imgUrl3.lastIndexOf("/") + 1, imgUrl3.length());
                            String typeStr3 = imgUrl3.substring(imgUrl3.lastIndexOf(".") + 1, imgUrl3.length());
                            picInfo.setPicFileName(nameStr3);
                            picInfo.setPicFileType(typeStr3);
                            String strBlob3 = MyUtils.bmpToBase64String(imgUrl3);
                            picInfo.setPicDataBlob(strBlob3);
                            picInfo.setWJLX("1");
                            listPic.add(picInfo);
                        }
                    }
                }
                handleAddJson.setPIC(listPic);
                ArrayList<HandleAddJson.CZFABean> czfaBeans = new ArrayList<>();
                for (int i = 0; i < Datas.size(); i++) {
                    HandleAddJson.CZFABean czfaBean = new HandleAddJson.CZFABean();
                    czfaBean.setGCXMID(Datas.get(i).getGCXMID());
                    czfaBean.setJSGS(Datas.get(i).getJSGS());
                    czfaBean.setHD("");
                    czfaBeans.add(czfaBean);
                }
                handleAddJson.setCZFA(czfaBeans);
                List<HandleAddJson> ssss = new ArrayList<>();
                ssss.add(handleAddJson);
                String json = new Gson().toJson(ssss);
                mPresenter.addLog(json, HandleAddActivity.this);
                break;
            case R.id.sgtp_im1:
                if (StringUtils.isEmpty(SGQTP)) {
                    TYPE = 1;
                    if (minePopupWindow == null) {
                        minePopupWindow = new MinePopupWindow(HandleAddActivity.this, itemOnClick);
                    }
                    minePopupWindow.showAtLocation(scrLay, Gravity.BOTTOM, 0, 0);
                }
                break;
            case R.id.sgtp_im2:
                if (StringUtils.isEmpty(SGHTP)) {
                    TYPE = 2;
                    if (minePopupWindow == null) {
                        minePopupWindow = new MinePopupWindow(HandleAddActivity.this, itemOnClick);
                    }
                    minePopupWindow.showAtLocation(scrLay, Gravity.BOTTOM, 0, 0);
                }
                break;
            case R.id.delete_im1:
                Glide.with(HandleAddActivity.this)
                        .load(R.drawable.img_add_pic)
                        .into(sgtpIm1);
                deleteIm1.setVisibility(View.GONE);
                SGQTP = "";
                break;
            case R.id.delete_im2:
                Glide.with(HandleAddActivity.this)
                        .load(R.drawable.img_add_pic)
                        .into(sgtpIm2);
                deleteIm2.setVisibility(View.GONE);
                SGHTP = "";
                break;
        }
    }

    private View.OnClickListener itemOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.mine_camera_btn:
                    if (minePopupWindow.isShowing()) {
                        minePopupWindow.dismiss();
                    }
                    getPicFromCamera();
                    break;
                case R.id.mine_photo_btn:
                    if (minePopupWindow.isShowing()) {
                        minePopupWindow.dismiss();
                    }
                    getPicFromPhoto();
                    break;
                case R.id.mine_cancel_btn:
                    if (minePopupWindow.isShowing()) {
                        minePopupWindow.dismiss();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 从相册获取
     */
    public void getPicFromPhoto() {
        Matisse.from(HandleAddActivity.this)
                .choose(MimeType.ofImage()) //显示所有文件类型，比如图片和视频，
                .isCrop(true)//开启裁剪，默认不开启
                .maxSelectable(1)
                .forResult(REQUEST_CODE_CHOOSE); //请求码
    }

    /**
     * 照相获取
     */
    public void getPicFromCamera() {
        Matisse.from(HandleAddActivity.this)
                .jumpCapture(CaptureMode.All)//只拍照片
                .isCrop(true)
                .forResult(REQUEST_CODE_CHOOSE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                if (TYPE == 1) {
                    SGQTP = Matisse.obtainCropResult(data);
                    Glide.with(HandleAddActivity.this)
                            .load(SGQTP)
                            .into(sgtpIm1);
                    deleteIm1.setVisibility(View.VISIBLE);
                } else if (TYPE == 2) {
                    SGHTP = Matisse.obtainCropResult(data);
                    Glide.with(HandleAddActivity.this)
                            .load(SGHTP)
                            .into(sgtpIm2);
                    deleteIm2.setVisibility(View.VISIBLE);
                }
            } else {
                final HandleAddGird handleAddGird = mapAdapter.get(childViewPosition);
                final ArrayList<Drawable> listPicture = handleAddGird.getListPicture();
                final ArrayList<String> listImgUrl = handleAddGird.getListImgUrl();
                String imgPath = Matisse.obtainCropResult(data);
                listPicture.remove(listPicture.size() - 1);
                Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
                if (bitmap != null) {
                    Drawable drawable = new BitmapDrawable(bitmap);
                    listPicture.add(drawable);
                    listImgUrl.add(imgPath);
                    Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
                    listPicture.add(addPicture);
                    handleAddGird.notifyDataSetChanged();
                }
            }
        }

    }

    @Override
    public void addLogs(String datas) {
        if (datas.equals("1")) {
            handleInfoDao.deleteByKey(getIntent().getLongExtra("RZID", 0));//根据id删除
            List<CzfaInfo> czfaInfo = czfaInfoDao.queryBuilder().where(CzfaInfoDao.Properties.ParentId.eq(getIntent().getLongExtra("RZID", 0))).list();
            czfaInfoDao.deleteByKey(czfaInfo.get(0).getId());
            ToastUtils.showShort("上传成功");
            Intent intent = new Intent();
            setResult(2, intent);
            finish();
        }
    }
}
